package com.ctsi.question.controller;

import com.ctsi.commons.util.UtilDateTime;
import com.ctsi.commons.util.UtilMisc;
import com.ctsi.commons.util.UtilValidate;
import com.ctsi.commons.util.request.UtilHttp;
import com.ctsi.commons.util.response.Page;
import com.ctsi.framework.common.response.UnifiedResponse;
import com.ctsi.framework.mybatis.support.VoTemplate;
import com.ctsi.framework.organise.security.UserInfo;
import com.ctsi.framework.security.util.SecurityUtil;
import com.ctsi.organise.entity.PersonEntity;
import com.ctsi.organise.service.PersonEntityManager;
import com.ctsi.question.entity.*;
import com.ctsi.question.service.ItemService;
import com.ctsi.question.service.MembersService;
import com.ctsi.question.service.PlanService;
import com.ctsi.question.vo.ItemVO;
import com.ctsi.question.vo.PlanVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @auth:wgf
 * @description :
 * @Date: 2019/7/26
 */
@RestController
public class ReportController {
    private static final Logger logger = LoggerFactory.getLogger(ReportController.class);

    @Autowired
    private ItemService itemService;
    @Autowired
    private VoTemplate voTemplate;
    @Autowired
    private MembersService membersService;
    @Autowired
    private PlanService planService;
    @Autowired
    private PersonEntityManager personEntityManager;

    /**
     * 添加/修改项目
     */
    @PostMapping(value = "/report/addItem",consumes = "application/json",produces = "application/json;charset=UTF-8")
    public UnifiedResponse<String> addItem(@RequestBody ItemEntity itemEntity){
        if (UtilValidate.isEmpty(itemEntity.getId())){
            UserInfo user = SecurityUtil.getUser();
            itemEntity.setCreateTime(System.currentTimeMillis());
            itemEntity.setCreateBy(user.getFullName());
            String s = itemService.insertItem(itemEntity);
            return UnifiedResponse.ok(s);
        }else {
            int i = itemService.updateItemById(itemEntity);
            return UnifiedResponse.ok(String.valueOf(i));
        }
    }
    /**
     * 项目详情
     */
    @PostMapping(value = "/report/selectItemById",produces = "application/json;charset=UTF-8" )
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<ItemEntity> selectItemById(@RequestParam("id") String id){
        if (UtilValidate.isEmpty(id)){
            return UnifiedResponse.ok(null);
        }
        ItemEntity itemEntity = itemService.selectItemById(id);
        return UnifiedResponse.ok(itemEntity);
    }
    /**
     * 删除项目
     *
     */
    @PostMapping(value = "/report/deleteItemById",produces = "application/json;charset=UTF-8")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<String> deleteItemById(@RequestParam("ids") String ids){
        if (UtilValidate.isNotEmpty(ids)) {
            List<String> arr = new ArrayList<>();
            if (!ids.contains(",")){
                arr.add(ids);
            } else {
                arr =  Arrays.asList(ids.split(","));
            }
            int result = arr.stream().parallel().filter(id -> UtilValidate.isNotEmpty(id)).mapToInt(id -> {
                try {
                    ItemEntity itemEntity=new ItemEntity();
                    itemEntity.setId(id);
                    itemEntity.setIs_delete(1);
                    return this.itemService.deleteItemById(itemEntity);
                }catch (Exception e){
                    logger.error("{}",e);
                    return 0;
                }
            }).sum();
            if(arr.size() >1){
                return UnifiedResponse.ok("选中"+arr.size()+"条数据，成功删除"+result+"条数据！");
            }else {
                return UnifiedResponse.ok("删除成功!");
            }
        }
        return UnifiedResponse.ok("删除成功!");
    }

    /**
     * 添加/修改项目成员
     */
    @PostMapping(value = "/report/addItemMember",consumes = "application/json",produces = "application/json;charset=UTF-8")
    public UnifiedResponse<Void> addItemMember(@RequestBody MembersEntity membersEntity){
        if (UtilValidate.isEmpty(membersEntity.getId())){
            PersonEntity personEntity = personEntityManager.selectIdByPhone(membersEntity.getMemberPhone());
            if (personEntity==null){
                return UnifiedResponse.error("1","该人员手机号不在系统内！");
            }else {
                membersEntity.setUserId(personEntity.getPartyId());
            }
            int i = membersService.insertItemMember(membersEntity);
            return UnifiedResponse.ok();
        }else {
            if (UtilValidate.isNotEmpty(membersEntity.getMemberPhone())){
                PersonEntity personEntity = personEntityManager.selectIdByPhone(membersEntity.getMemberPhone());
                if (personEntity==null){
                    return UnifiedResponse.error("1","该人员手机号不在系统内！");
                }else {
                    membersEntity.setUserId(personEntity.getPartyId());
                }
            }
            int i = membersService.updateItemMemberById(membersEntity);
            return UnifiedResponse.ok();
        }
    }
    /**
     * 查询项目成员详情
     */
    @PostMapping(value = "/report/selectItemMemberById",produces = "application/json;charset=UTF-8" )
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<MembersEntity> selectItemMemberById(@RequestParam("id") String id){
        if (UtilValidate.isEmpty(id)){
            return UnifiedResponse.ok(null);
        }
        MembersEntity membersEntity = membersService.selectItemMemberById(id);
        return UnifiedResponse.ok(membersEntity);
    }
    /**
     * 删除项目成员
     */
    @PostMapping(value = "/report/deleteItemMemberById",produces = "application/json;charset=UTF-8")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Integer> deleteItemMemberById(@RequestParam("id") String id){
        if (UtilValidate.isNotEmpty(id)) {
                    MembersEntity membersEntity=new MembersEntity();
                    membersEntity.setId(id);
                    membersEntity.setIs_delete(1);
            int i = membersService.updateItemMemberById(membersEntity);
            return UnifiedResponse.ok(i);
        }else {
            return UnifiedResponse.ok(0);
        }
    }
    /**
     * 添加及更新项目计划
     */
    @PostMapping(value = "/report/addItemPlan",consumes = "application/json",produces = "application/json;charset=UTF-8")
    public UnifiedResponse<Integer> addItemPlan(@RequestBody PlanEntity planEntity){
        if (UtilValidate.isEmpty(planEntity.getId())){
            long start = planEntity.getStartTime();
            long end = planEntity.getEndTime();
            planEntity.setStartTime(UtilDateTime.getDayStart(new Date(start)));
            planEntity.setEndTime(UtilDateTime.getDayEnd(new Date(end)));
            int i = planService.insertItemPlan(planEntity);
            return UnifiedResponse.ok(i);
        }else {
            long start = planEntity.getStartTime();
            long end = planEntity.getEndTime();
            planEntity.setStartTime(UtilDateTime.getDayStart(new Date(start)));
            planEntity.setEndTime(UtilDateTime.getDayEnd(new Date(end)));
            int i = planService.updateItemPlanById(planEntity);
            return UnifiedResponse.ok(i);
        }
    }
    /**
     * 查询项目计划详情
     */
    @PostMapping(value = "/report/selectItemPlanById",produces = "application/json;charset=UTF-8" )
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<PlanEntity> selectItemPlanById(@RequestParam("id") String id){
        if (UtilValidate.isEmpty(id)){
            return UnifiedResponse.ok(null);
        }
        PlanEntity planEntity = planService.selectItemPlanById(id);
        return UnifiedResponse.ok(planEntity);
    }
    /**
     * 删除项目计划
     */
    @PostMapping(value = "/report/deleteItemPlanById",produces = "application/json;charset=UTF-8")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Integer> deleteItemPlanById(@RequestParam("id") String id){
        if (UtilValidate.isNotEmpty(id)) {
                    PlanEntity planEntity=new PlanEntity();
                    planEntity.setId(id);
                    planEntity.setIs_delete(1);
            int i = planService.updateItemPlanById(planEntity);
            return UnifiedResponse.ok(i);
        }else {
            return UnifiedResponse.ok(0);
        }
    }
    /**
     * 项目列表
     */
    @PostMapping(value = "/report/queryItemList",consumes = "application/json",produces = "application/json;charset=UTF-8")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Page<ItemVO>> queryItemList(@RequestBody ItemQuery ppp){
        if (UtilValidate.isNotEmpty(ppp.getCustomer())){
            ppp.setCustomer("%"+ppp.getCustomer()+"%");
        }
        if (UtilValidate.isNotEmpty(ppp.getItemName())){
            ppp.setItemName("%"+ppp.getItemName()+"%");
        }
        Page<ItemEntity> result = itemService.selectMulitCondition(UtilHttp.filterBlank(UtilMisc.toMap(ppp)),ppp.getStart(),ppp.getPageSize());
        List<ItemVO> itemVOS=result.getResult().stream().map(lib ->{
            ItemVO itemVO=voTemplate.defaultExcute(new ItemVO(),lib);
            itemVO.setCreateTimeStr(UtilDateTime.longToString(lib.getCreateTime()));
            itemVO.setCurrentRate(lib.getCurrentRate()+"%");
            return itemVO;
        }).collect(Collectors.toList());
        return UnifiedResponse.ok(new Page<>(ppp.getStart(),result.getTotalCount(),result.getPageSize(),itemVOS));
    }
    /**
     * 项目成员列表
     */
    @PostMapping(value = "/report/queryItemMembersList",consumes = "application/json",produces = "application/json;charset=UTF-8")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Page<MembersEntity>> queryItemMembersList(@RequestBody MembersQuery ppp){
        Page<MembersEntity> result = membersService.selectMulitCondition(UtilHttp.filterBlank(UtilMisc.toMap(ppp)),ppp.getStart(),ppp.getPageSize());
        return UnifiedResponse.ok(result);
    }
    /**
     * 项目计划列表
     */
    @PostMapping(value = "/report/queryItemPlanList",consumes = "application/json",produces = "application/json;charset=UTF-8")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Page<PlanVO>> queryItemPlanList(@RequestBody MembersQuery ppp){
        Page<PlanEntity> result = planService.selectMulitCondition(UtilHttp.filterBlank(UtilMisc.toMap(ppp)),ppp.getStart(),ppp.getPageSize());
        List<PlanVO> planVOS=result.getResult().stream().map(lib ->{
            PlanVO planVO=voTemplate.defaultExcute(new PlanVO(),lib);
            planVO.setStartTimeStr(UtilDateTime.longToString(lib.getStartTime()));
            planVO.setEndTimeStr(UtilDateTime.longToString(lib.getEndTime()));
            planVO.setPlanSpeed(lib.getPlanSpeed()+"%");
            return planVO;
        }).collect(Collectors.toList());
        return UnifiedResponse.ok(new Page<>(ppp.getStart(),result.getTotalCount(),result.getPageSize(),planVOS));
    }

}
